package com.example.oauth.secutity.filter;

import java.io.IOException;
import java.util.Optional;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.lang.Nullable;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.StringUtils;

public class SinoLoginAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
	
	
	
	public static final String SPRING_SECURITY_FORM_USERNAME_KEY = "username";
	public static final String SPRING_SECURITY_FORM_PASSWORD_KEY = "password";

	private String usernameParameter = SPRING_SECURITY_FORM_USERNAME_KEY;
	private String passwordParameter = SPRING_SECURITY_FORM_PASSWORD_KEY;
	
	
	private boolean postOnly = true;

	public SinoLoginAuthenticationFilter() {
		super(new AntPathRequestMatcher("/sinoLogin", "POST"));
	}
	


	@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
			throws AuthenticationException, IOException, ServletException {
		
		
		
		if (postOnly && !request.getMethod().equals("POST")) {
			throw new AuthenticationServiceException(
					"Authentication method not supported: " + request.getMethod());
		}

		String username = obtainUsername(request);
		String password = obtainPassword(request);

		if (username == null) {
			username = "";
		}

		if (password == null) {
			password = "";
		}
		
		
		request.getSession().removeAttribute(username);
		
		
		SinoAuthenticationToken authRequest = new SinoAuthenticationToken(
				username, password);

		return super.getAuthenticationManager().authenticate(authRequest);
	}
	

	@Nullable
	protected String obtainPassword(HttpServletRequest request) {
		return request.getParameter(passwordParameter);
	}
	
	protected String obtainUsername(HttpServletRequest request) {
		return request.getParameter(usernameParameter);
	}
	
	
	
	/**
	 * 	根据用户名从session中获取短信验证码
	 * @param request
	 * @return
	 */
	protected String getSessionSmsCode(HttpServletRequest request) {
		return Optional
				.ofNullable(request.getSession().getAttribute(this.obtainUsername(request)))
				.orElse("")
				.toString();
		
	}
	
}
